from typing import List, Optional
from sqlalchemy.orm import Session

from models.NewInfoPush import NewInfoPush
from schemas.NewInfoPush import NewInfoPushCreate, NewInfoPushUpdate


class NewInfoPushService:
    """
    新信息推送服务类，提供新信息推送相关的业务逻辑
    """

    def get_by_id(self, db: Session, id: int) -> Optional[NewInfoPush]:
        """
        根据 ID 获取新信息推送
        """
        return db.query(NewInfoPush).filter(NewInfoPush.id == id, NewInfoPush.isDelete == False).first()

    def get_all(self, db: Session, skip: int = 0, limit: int = 10000) -> List[NewInfoPush]:
        """
        获取所有未删除的新信息推送
        """
        return db.query(NewInfoPush).filter(NewInfoPush.isDelete == False).offset(skip).limit(limit).all()

    def get_by_email(self, db: Session, email: str) -> List[NewInfoPush]:
        """
        根据邮箱获取新信息推送
        """
        return db.query(NewInfoPush).filter(
            NewInfoPush.email == email,
            NewInfoPush.isDelete == False
        ).all()
    def get_by_email_first(self, db: Session, email: str) -> NewInfoPush:
        """
        根据邮箱获取新信息推送
        """
        return db.query(NewInfoPush).filter(
            NewInfoPush.email == email,
            NewInfoPush.isDelete == False
        ).first()

    def create(self, db: Session, new_info_push: NewInfoPushCreate) -> NewInfoPush:
        """
        创建新的信息推送
        """
        # 不需要指定 id，因为是自增的
        db_new_info_push = NewInfoPush(
            email=new_info_push.email,
            count=new_info_push.count,
            # isDelete 有默认值，不需要指定
        )
        db.add(db_new_info_push)
        db.commit()
        db.refresh(db_new_info_push)
        return db_new_info_push

    def update(self, db: Session, new_info_push_id: int, new_info_push_update: NewInfoPushUpdate) -> Optional[
        NewInfoPush]:
        """
        更新新信息推送
        """
        db_new_info_push = db.query(NewInfoPush).filter(NewInfoPush.id == new_info_push_id).first()
        if db_new_info_push is None:
            return None

        # 更新字段
        update_data = new_info_push_update.dict(exclude_unset=True)
        for key, value in update_data.items():
            setattr(db_new_info_push, key, value)

        db.commit()
        db.refresh(db_new_info_push)
        return db_new_info_push

    def delete(self, db: Session, new_info_push_id: int) -> bool:
        """
        软删除新信息推送
        """
        db_new_info_push = db.query(NewInfoPush).filter(NewInfoPush.id == new_info_push_id).first()
        if db_new_info_push is None:
            return False

        db_new_info_push.isDelete = True
        db.commit()
        return True

    def check_email_exists(self, db: Session, email: str) -> bool:
        """
        检查邮箱是否已存在
        """
        return db.query(NewInfoPush).filter(
            NewInfoPush.email == email,
            NewInfoPush.isDelete == False
        ).first() is not None
